<template>
    <a-popover
        v-model:open="visible"
        title="Title"
        @openChange="handleClick"
        trigger="click"
    >
        <template #content>
            <div @mousedown.stop.prevent>
                <a-button
                    v-for="(item, index) in pyList"
                    :key="index"
                    type="dashed"
                    shape="circle"
                    style="margin-right: 10px"
                    @click="handleItemClick(item)"
                >
                    {{ item.label }}
                </a-button>
            </div>
        </template>
        <a-button type="primary" style="padding: 0 10px; margin-left: 10px">
            多音字
        </a-button>
    </a-popover>
</template>
<script setup>
import { ref, watch } from "vue";

import PinyinFn from "./pinyin-fn.js";

import {
    polyphoneDataToLabelValue,
    getPolyphoneData,
} from "../../utils/pinyin.js";
import { message } from "ant-design-vue";

const fn = ref();
const pyList = ref([]);
const visible = ref(false);
const onOpen = (editor) => {
    if (!fn.value && editor) {
        // console.log('onOpen')
        fn.value = new PinyinFn(editor);
    }
};

function getPinyinList(word) {
    const polyphoneData = getPolyphoneData(word);
    return polyphoneDataToLabelValue(polyphoneData);
}
async function handleClick(status) {
    console.log("handleClick:", status);
    if (!status) return;
    if (fn.value.isDisabled()) {
        visible.value = false;
        return;
    }

    const text = fn.value.getValue();
    console.log("text:", text);
    if (text) {
        var result = getPinyinList(text);

        pyList.value = result;
        if (pyList.value.length > 1) {
            return;
        } else {
            visible.value = false;
            message.warn("选中的字符不是多音字");
            return;
        }
    } else {
        pyList.value = [];
        visible.value = false;
        // message.warn("请选择中文字");
    }
}

function handleItemClick(item) {
    console.log("handleItemClick:", item);
    fn.value?.exec({ ...item });
    pyList.value = [];
    visible.value = false;
}

const props = defineProps({
    editor: {
        type: Object,
        default: null,
    },
});

watch(
    () => props.editor,
    (val) => {
        // console.log("props.editor", props.editor);
        onOpen(props.editor);
    },
    { immediate: true, deep: true }
);

// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
    onOpen,
});
</script>
